package greedy;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description: 1005. K 次取反后最大化的数组和
 * User: Li_yizYa
 * Date: 2025/6/25
 * Time: 19:31
 */
public class Solution7 {
    public int largestSumAfterKNegations(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length && k > 0; i++) {
            if (nums[i] >= 0) {
                break;
            }
            nums[i] = -nums[i];
            k--;
        }
        Arrays.sort(nums);
        if (k % 2 == 1) {
            nums[0] = -nums[0];
        }
        int ret = 0;
        for (int num : nums) {
            ret += num;
        }
        return ret;
    }
}
